//
//  HMNetworkTools.swift
//  06-Swift网络封装
//
//  Created by apple on 17/1/17.
//  Copyright © 2017年 apple. All rights reserved.
//

import UIKit
import AFNetworking


// 请求方式的枚举(可以支持字符串的类型)
enum HMNetworkToolsMethod:String {
    case get = "get"
    case post = "post"
}

class HMNetworkTools: AFHTTPSessionManager {
    // 全局访问点
    static let shared:HMNetworkTools = {
        let tools = HMNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        return tools
    }()
    
    /// 网络请求公共方法
    ///
    /// - Parameters:
    ///   - method: 请求方式
    ///   - urlString: 请求url
    ///   - parameters: 请求参数
    ///   - success: 成功的闭包
    ///   - failure: 失败的闭包
    func request(method: HMNetworkToolsMethod, urlString: String, parameters: Any?, success:@escaping (Any?)->(), failure:@escaping (Error)->()){
        // 如果是get请求
        if method == .get {
            
            self.get(urlString, parameters: parameters, progress: nil, success: { (_, res) in
                // 执行闭包
                success(res)
            }, failure: { (_, err) in
                // 执行闭包
                failure(err)
            })
        }else {
            // post 请求
            self.post(urlString, parameters: parameters, progress: nil, success: { (_, res) in
                // 执行闭包
                success(res)
            }, failure: { (_, err) in
                // 执行闭包
                failure(err)
            })
        }
    }
    
  

}

//MARK: - 请求首页数据
extension HMNetworkTools{
    
    func loadData(since_id:Int64, max_id:Int64,success:@escaping (Any?)->(), failure:@escaping (Error)->()){
        //url
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //请求参数
        let params = ["access_token":ZZOAuthViewModel.shared.accessToken!,
                      "since_id": since_id,
                      "max_id": max_id] as [String : Any]
        //请求数据
        request(method: HMNetworkToolsMethod.get, urlString: urlString, parameters: params, success: success, failure: failure)
    }
    
    
}



//MARK: - OAuth网络请求
extension HMNetworkTools{
    //请求获取accessToken
    func loadUserAccount(code:String,success:@escaping (Any?)->(), failure:@escaping (Error)->()){
        //请求的URL
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //请求参数
        let params = [
            
            "client_id" : APPKEY,
            "client_secret" : APPSECRET,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : REDIRECT_URI
            
        ]
        //发送请求
        request(method: HMNetworkToolsMethod.post, urlString: urlString, parameters: params, success: success, failure: failure)
    }
    //获取用户请求信息数据
    func loadUserInfo(userAccountModel: ZZUserAccountModel,success:@escaping (Any?)->(), failure:@escaping (Error)->()){
        //请求的url
        let urlString = "https://api.weibo.com/2/users/show.json"
        //请求的参数
        let params = [
            "access_token": userAccountModel.access_token!,
            "uid": userAccountModel.uid!
        ]
        //发送请求
        request(method: HMNetworkToolsMethod.get, urlString: urlString, parameters: params, success: success, failure: failure)
        
    }
    
    
}
//MARK: - 发布微博
extension HMNetworkTools {
    //发布文字微博
    func upDate(status: String,success:@escaping (Any?)->(), failure:@escaping (Error)->()){
        let url = "https://api.weibo.com/2/statuses/update.json"
        //请求参数
        let params = [
            "access_token" : ZZOAuthViewModel.shared.accessToken!,
            "status": status
            ] as [String : Any]
        
        //发送请求
        //发送请求
        request(method: HMNetworkToolsMethod.post, urlString: url, parameters: params, success: success, failure: failure)
    }
    
    //发布图片文字微博
    func upload(status: String,images: [UIImage],success:@escaping (Any?)->(), failure:@escaping (Error)->()){
        //url
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        //请求参数
        let params = [
            "access_token" : ZZOAuthViewModel.shared.accessToken!,
            "status": status
            ] as [String : Any]
        
        post(url, parameters: params, constructingBodyWith: { (formdata) in
            
            let data = UIImagePNGRepresentation(images.first!)!
            formdata.appendPart(withFileData: data, name: "pic", fileName: "xxx", mimeType: "application/octet-stream")
            //            // 如果一次发布9张图片怎么办 -> 通过循环方式上传
            //            for image in self.composePictureView.images {
            //                let data = UIImagePNGRepresentation(image)!
            //                formdata.appendPart(withFileData: data, name: "pic", fileName: "xxxx", mimeType: "application/octet-stream")
            //            }

        }, progress: nil, success: { (_, res) in
            success(res)
        }) { (_, error) in
            failure(error)
        }
    }
    
    
}
